package com.itheima.tliasproject.controller;


import com.itheima.tliasproject.pojo.AliOSSProperties;
import com.itheima.tliasproject.pojo.Result;
import com.itheima.tliasproject.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class UpLoadController {



//    private final String bucketName = "web-talis-xiaoxiong";
//    private final String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    // 从配置文件读取OSS参数
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;
//
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;

    @Autowired
   private AliOSSProperties aliOSSProperties;

    /**
     * 文件上传--阿里云OSS存储
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        //1.获取原始文件名，截取后缀
        String originalFilename = file.getOriginalFilename();  //eg:1.2.3.jpg
        log.info("原始文件名: {}", originalFilename);
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));  //获取后缀

        //2.调用阿里云OSS工具类，将文件上传到oss
        String url = AliyunOSSUtils.upload(aliOSSProperties.getEndpoint(), aliOSSProperties.getBucketName(), file.getBytes(), extName);

        //3.返回图片路径
        return Result.Success(url);
    }
}
